package org.apache.ocean.name;

import java.io.File;
import java.net.URL;
import java.util.logging.Logger;

import org.apache.ocean.AppServerUtil;
import org.apache.ocean.ClusterUtil;
import org.apache.ocean.XMLUtil;
import org.jdom.Element;

/**
 *
 * @author jasonr
 */
public class NameConfig {
  public static Logger log = Logger.getLogger(NameConfig.class.getName());
  public File databaseDirectory;
  public File filesDirectory;
  public File nameURLsFile;
  public File idFile;
  public URL url;
  
  public static NameConfig loadNameConfig() throws Exception {
    //ClusterUtil.printSystemProperties(log);
    File nameHome = ClusterUtil.getNameHome();
    File configFile = new File(nameHome, "config.xml");
    Element element = XMLUtil.parseElement(configFile);
    NameConfig nameConfig = null;
    if (element != null) {
      nameConfig = (NameConfig)ClusterUtil.construct(element, NameConfig.class);
    } else nameConfig = new NameConfig();
    if (nameConfig.url == null) {
      throw new Exception("url missing in config");
    }
    if (nameConfig.databaseDirectory == null) nameConfig.databaseDirectory = new File(nameHome, "database");
    if (nameConfig.filesDirectory == null) nameConfig.filesDirectory = new File(nameHome, "files");
    if (nameConfig.nameURLsFile == null) nameConfig.nameURLsFile = new File(nameHome, "names.txt");
    if (!nameConfig.nameURLsFile.exists()) throw new Exception(nameConfig.nameURLsFile.getAbsolutePath()+" does not exist");
    if (nameConfig.idFile == null) nameConfig.idFile = new File(nameHome, "id.txt");
    return nameConfig;
  }
  
  public NameConfig() {}
  
  public NameConfig(Element element) throws Exception {
    XMLUtil.reflectToObject(this, element);
  }
}
